package cn.starrysky.hrm.service.impl;

import cn.starrysky.hrm.dto.SmsCodeDto;
import cn.starrysky.hrm.exception.GlobalException;
import cn.starrysky.hrm.service.IVerifycodeService;
import cn.starrysky.hrm.util.StrUtils;
import cn.starrysky.hrm.util.VerifyCodeUtils;
import cn.starrysky.hrm.utils.ValidUtils;
import cn.starrysky.hrm.vo.SendSmsCodeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String getImageCode(String key) {
        //获取key
        //System.out.println(key);
        //校验key
        ValidUtils.assertNotNull(key, "系统错误，请刷新重试！");
        //生成校验码
        String imageCode = UUID.randomUUID().toString().substring(1, 5);
        //保存redis 10分钟有效
        redisTemplate.opsForValue().set(key, imageCode,10, TimeUnit.MINUTES);
        //合并图片 base64编码
        //返回
        return VerifyCodeUtils.verifyCode(140, 40, imageCode);

    }

    /**
     * 发送短信验证码
     * @param dto
     */
    @Override
    public void sendSmsCode(SmsCodeDto dto) {
        //校验
        String imageCode = dto.getImageCode();
        String imageCodeKey = dto.getImageCodeKey();
        String mobile = dto.getMobile();
        ValidUtils.assertNotNull(imageCode, "图片验证码不能为空");
        ValidUtils.assertNotNull(imageCodeKey, "系统错误，请刷新重试！");
        ValidUtils.assertNotNull(mobile, "手机号不能为空");
        //校验图片验证码是否正确
        //查询图片验证吗
        String imageCodeFromRedis=(String) redisTemplate.opsForValue().get(imageCodeKey);
        ValidUtils.assertNotNull(imageCodeFromRedis, "图片验证码已过期！");
        ValidUtils.assertNotSame(imageCode,imageCodeFromRedis,"图片验证码错误！" );


        //当前时间 毫秒值
        long nowTime = new Date().getTime();
        String smsCode=null; //验证码
        //短信验证码key
        String smsCodeKey="sms:"+mobile;
        //判断是否有上一次没用的验证码
        SendSmsCodeVo sendSmsCodeVo= (SendSmsCodeVo)redisTemplate.opsForValue().get(smsCodeKey);
        if (sendSmsCodeVo!=null){  //如果有
            //判断距离上次发送间隔60s
            Long sendTime = sendSmsCodeVo.getSendTime();
            if ((nowTime-sendTime)/1000<=60){ //如果小于60s就是发送频繁
                throw  new GlobalException("短信发送频繁，请稍后再试！");
            }
            smsCode=sendSmsCodeVo.getSmsCode();
        }else { //如果没有上次发送
            //生成短信验证码
            smsCode = StrUtils.getRandomString(4);
        }
        //存入redis
        redisTemplate.opsForValue().set(smsCodeKey, new SendSmsCodeVo(smsCode,nowTime),10,TimeUnit.MINUTES);
        //调用发送短信
        //System.out.println("短信验证码为："+smsCode);
        log.info("短信验证码为："+smsCode);
        //记录日志保存数据库
        log.info("手机验证码日志已经保存到数据库oK");

    }


}
